<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="success" @click="addRoles">增加角色</el-button>
        </el-col>
      </el-row>
      <el-table class="margin-top1" :data="rolesList" border style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称">
          <template slot-scope="scope">
            <el-link type="primary" @click="RoleClick(scope.row)">{{scope.row.roleName}}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width='420'>
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              @click="delRoles(scope.row)"
              icon="el-icon-delete"
            >删除角色</el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-edit"
              @click="editeRoles(scope.row.id)"
            >编辑角色</el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-star-off"
              @click="rightlistnum(scope.row)"
            >管理权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 增加角色对话框 -->
    <el-dialog title="增加角色" :visible.sync="addDialogVisible" width="50%" @close="addrest">
      <el-form :model="RolesForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="RolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesMethod">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editeDialogVisible" width="50%" @close="editerest">
      <el-form :model="RolesForm" :rules="addFormRules" ref="editeFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="RolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editeRolesMethod">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色权限对话框 -->
    <el-dialog title="角色对应权限" :visible.sync="roleDialogVisible" width="70%">
      <el-row
        :class="['vcenter',index1===0 ? '' : 'marg-border']"
        v-for="(item1,index1) in roleInfo"
        :key="item1.id"
      >
        <el-col :span="5">
          <el-tag closable @close="rightClose(item1.id)" type="primary">{{item1.authName}}</el-tag>
          <i class="el-icon-caret-right"></i>
        </el-col>
        <el-col :span="19">
          <!-- 二级权限 和 三级权限 -->
          <el-row
            :class="['vcenter',index2===0 ? '' : 'marg-border']"
            v-for="(item2,index2) in item1.children"
            :key="item2.id"
          >
            <el-col :span="6">
              <el-tag @close="rightClose(item2.id)" closable type="success">{{item2.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="18">
              <el-tag
                closable
                @close="rightClose(item3.id)"
                style="margin:5px 5px;"
                :class="index3"
                type="warning"
                v-for="(item3,index3) in item2.children"
                :key="item3.id"
              >{{item3.authName}}</el-tag>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 管理权限对话框 -->
    <el-dialog title="权限管理列表" :visible.sync="rightDialogVisible" width="70%" @close="restdefkeyid">
      <el-tree
        ref="treeRef"
        :data="rightList"
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeyid"
        show-checkbox
        :props="defaultProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getRolesList();
  },
  data() {
    return {
      defkeyid: [],
      rolesList: [],
      RolesForm: {
        roleName: "",
        roleDesc: ""
      },
      editeRolesId: "",
      addDialogVisible: false,
      editeDialogVisible: false,
      roleDialogVisible: false,
      rightDialogVisible: false,
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      },
      roleInfo: {}, //角色对应权限数据
      roleInfoId: 0,
      rightList: [], //权限列表
      defaultProps: {
        children: "children",
        label: "authName"
      }
    };
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      //   console.log(res.data);
    },
    // 添加角色
    addRoles() {
      this.addDialogVisible = true;
    },
    addRolesMethod() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.RolesForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.addDialogVisible = false;
        this.getRolesList();
      });
    },
    addrest() {
      this.$refs.addFormRef.resetFields();
    },
    // 编辑事件
    async editeRoles(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editeRolesId = id;
      this.RolesForm = res.data;
      this.editeDialogVisible = true;
    },
    editeRolesMethod() {
      this.$refs.editeFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editeRolesId,
          this.RolesForm
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.editeDialogVisible = false;
        this.getRolesList();
      });
    },
    editerest() {
      this.RolesForm = {
        roleName: "",
        roleDesc: ""
      };
    },
    // 删除事件
    async delRoles(info) {
      let del = await this.$confirm(
        `此操作将永久删除该${info.roleName}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (del !== "confirm") return this.$message.info("取消了删除");
      const { data: res } = await this.$http.delete("roles/" + info.id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRolesList();
    },
    // 角色点击获取对应的数据 渲染为tag进行渲染
    RoleClick(roleInfo) {
      this.roleInfo = roleInfo.children;
      this.roleInfoId = roleInfo.id;
      this.roleDialogVisible = true;
    },
    // 点击叉号删除对应角色权限
    async rightClose(rightid) {
      let del = await this.$confirm(`此操作将删除该权限, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (del !== "confirm") return this.$message.info("取消了删除");
      const { data: res } = await this.$http.delete(
        `roles/${this.roleInfoId}/rights/${rightid}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.roleInfo = res.data;
      this.$message.success(res.meta.msg);
    },
    // 获取权限数据
    async rightlistnum(rights) {
      const { data: res } = await this.$http.get("rights/tree");
      this.rightList = res.data;
      this.roleInfoId = rights.id;
      this.getleafkeys(rights, this.defkeyid);
      this.rightDialogVisible = true;
    },
    // 权限管理保存
    async setRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      
      const idstr = keys.join(",");
      console.log(idstr)
      const {
        data: res
      } = await this.$http.post(`roles/${this.roleInfoId}/rights`, {
        rids: idstr
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getRolesList()
      this.$message.success(res.meta.msg);
      this.rightDialogVisible=false
    },
    // 定义递归拿id
    getleafkeys(node, arr) {
      if (!node.children) return arr.push(node.id);
      node.children.forEach(element => {
        this.getleafkeys(element, arr);
      });
    },
    restdefkeyid() {
      this.defkeyid = [];
    }
  }
};
</script>
<style lang="less" scoped>
.marg-border {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
  padding: 10px 0;
}
</style>
